
/**
 * 新增/修改cookie的值
 * @param {string} key cookie的key
 * @param {string|number} val cookie的值
 * @param {string|number} expires cookie的过期时间（string）/存活时间（秒）
 */
function setCookie(key, val, expires) {
    expires = typeof expires !== 'string'
        ? new Date(Date.now() - 8 * 3600 * 1000 + expires * 1000).toString()
        : expires;
    document.cookie = `${key}=${val};expires=${expires}`
}

/**
 * 删除指定的cookie 通过覆盖来让其立刻过期
 * @param {string} key
 */
function removeCookie(key) {
    document.cookie = `${key}=${null};expires=${new Date(
        Date.now() - 8 * 3600 * 1000 - 1
    ).toString()}`;
}

/**
 * 获取指定的cookie 
 * @param {string} key
 */
function getCookie(key) {
    let obj = {}
    let cookie = document.cookie.split("; ")
    for (let i = 0; i < cookie.length; i++) {
        const [k, v] = cookie[i].split('=');
        if (key === k) {
            obj[k] = v
            return v
        }
    }
}

export {
    getCookie,
    setCookie,
    removeCookie
}

